<template>
  <el-form :form="form" label-width="150px" label-position="right" class="psnInfo-form">
    <el-form-item label="用户名:">
      <el-input v-model="form.name" placeholder="请输入用户名"></el-input>
    </el-form-item>
    <el-form-item label="密码:">
      <el-input type="password" v-model="form.pwd" placeholder="请输入密码"></el-input>
    </el-form-item>
    <el-form-item label="用户类型:">
      <el-select v-model="form.type" placeholder="请选择用户类型">
        <el-option label="管理员" value="1"></el-option>
        <el-option label="普通用户" value="2"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="用户状态:">
      <el-select v-model="form.state" placeholder="请选择用户状态">
        <el-option label="可用" value="1"></el-option>
        <el-option label="不可用" value="2"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="邮箱:">
      <el-input v-model="form.email" placeholder="请输入邮箱"></el-input>
    </el-form-item>
    <el-form-item>
      <p class="btn-area tr">
        <el-button type="warning" @click="cancel">重置</el-button>
        <el-button type="primary" @click="submmit">提交</el-button>
      </p>
    </el-form-item>
  </el-form>
</template>

<script>
import { reactive, ref, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import request from 'request/index';
import { ElNotification } from 'element-plus';
import store from '../store/index';
export default {
  name: 'psnInfo',
  setup() {
    const router = useRouter(),
      route = useRoute();

    const user = store.getters['user/userInfo'];

    const form = reactive(
      Object.assign(
        {},
        {
          _id: '',
          name: '',
          pwd: '',
          state: '',
          type: '',
          email: ''
        },
        user
      )
    );
    let form_back = {};

    const requestEdit = () => {
      let params = Object.assign({}, form, { _id: user._id });

      request.post('/user/update', params).then(data => {
        if (data.state == 200) {
          ElNotification({
            message: '用户修改成功!',
            type: 'success'
          });
        }
      });
    };

    const submmit = () => {
      requestEdit();
    };
    const cancel = () => {
      Object.keys(form).forEach(key => {
        form[key] = form_back[key];
      });
    };

    onMounted(() => {
      request.get('/user/detail', { _id: user._id }).then(resp => {
        Object.keys(form).forEach(key => {
          form[key] = resp.data[key];
        });
        form_back = JSON.parse(JSON.stringify(form));
      });
    });

    return {
      form,
      submmit,
      cancel
    };
  }
};
</script>

<style lang="scss" scoped>
.psnInfo-form {
  width: 70%;
}
.psnInfo-form .el-form-item__content .el-select {
  width: 100%;
}
</style>
